package com.mystudy.netty.echo.version_1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @author 周志龙
 * @Email 15216876513@163.com
 * @Date on 2019/10/24 0:48
 * @Description 客户端引导类
 */
public class EchoClient {
    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(EchoClient.class);
    private String host;
    private int port;

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        String host = "127.0.0.1";
        int port = 10000;
        new EchoClient(host, port).start();
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect().sync();
            LOGGER.debug("channel = [{}]",future.channel());
            LOGGER.debug("尝试关闭channel");
            LOGGER.debug("future = [{}]",future);
            ChannelFuture closeFuture = future.channel().closeFuture();
            LOGGER.debug("closeFuture = [{}]",closeFuture);
            closeFuture.sync();
            LOGGER.debug("关闭channel成功");
        } finally {
            LOGGER.debug("尝试关闭group");
            group.shutdownGracefully().sync();
            LOGGER.debug("关闭group成功");
        }

    }
}
